package dal

import (
	"go-admin-auth/app/models"
	"go-admin-auth/conn/mysql_conn"
	"go-admin-auth/httpapi/dto"
	"gorm.io/gorm"
)

type userRoleDAO struct{}

var (
	UserRoleDAO = &userRoleDAO{}
)

func (d *userRoleDAO) Query(f *dto.UserRoleQueryForm) (*dto.UserRoleQueryRes, error) {
	session := d.newSession()

	var total int64
	var list []models.TUserRole

	if f.UserId != 0 {
		session.Where("user_id = ?", f.UserId)
	}

	if f.RoleId != 0 {
		session.Where("role_id = ?", f.RoleId)
	}

	if len(f.OrderBy) > 0 {
		for _, v := range f.OrderBy {
			session.Order(v)
		}
	}

	if err := session.Count(&total).Error; err != nil {
		return nil, err
	}
	if err := session.Limit(f.Limit()).Offset(f.Offset()).Find(&list).Error; err != nil {
		return nil, err
	}

	return &dto.UserRoleQueryRes{Total: total, List: list}, nil
}

func (d *userRoleDAO) GetList(f *dto.UserRoleQueryForm) ([]models.TUserRole, error) {
	var results []models.TUserRole

	session := d.newSession()

	if f.UserId != 0 {
		session.Where("user_id = ?", f.UserId)
	}

	if f.RoleId != 0 {
		session.Where("role_id = ?", f.RoleId)
	}

	err := session.Limit(f.Limit()).Offset(f.Offset()).Find(&results).Error
	if err != nil {
		return nil, err
	}
	return results, nil
}

func (d *userRoleDAO) Get(id int) (*models.TUserRole, error) {
	info := &models.TUserRole{}
	session := d.newSession()
	if err := session.Where("id= ?", id).First(info).Error; err != nil {
		return nil, err
	}

	return info, nil
}

func (d *userRoleDAO) GetMulti(idList []int) (map[int]models.TUserRole, error) {
	var mMap = make(map[int]models.TUserRole, 0)
	var results []models.TUserRole

	session := d.newSession()
	query := session.Where("id IN ?", idList)
	err := query.Find(&results).Error
	if err != nil {
		return nil, err
	}
	for _, v := range results {
		mMap[v.Id] = v
	}
	return mMap, nil
}

func (d *userRoleDAO) BatchInsert(m []*models.TUserRole) error {
	session := d.newSession()
	err := session.Create(m).Error
	return err
}

func (d *userRoleDAO) Insert(m *models.TUserRole) error {
	session := d.newSession()
	err := session.Create(m).Error
	return err
}

func (d *userRoleDAO) Update(m *models.TUserRole) error {
	session := d.newSession()
	err := session.Where("id = ?", m.Id).UpdateColumns(m).Error
	return err
}

func (d *userRoleDAO) RealDeleteByUserId(userId int) error {
	session := d.newSession()
	err := session.Where("user_id = ?", userId).Delete(models.TUserRole{}).Error
	return err
}

func (d *userRoleDAO) RealDelete(id int) error {
	session := d.newSession()
	err := session.Where("id = ?", id).Delete(models.TUserRole{}).Error
	return err
}

func (d *userRoleDAO) newEngine() *gorm.DB {
	return mysql_conn.GetDb()
}

func (d *userRoleDAO) newSession() *gorm.DB {
	return mysql_conn.GetSession().Table("t_user_role")
}
